package com.locus.tools.location;

import com.google.android.maps.Overlay;
import com.locus.tools.xmpp.GTalkAgent;
import com.locus.tools.xmpp.GTalkFailedException;
import com.locus.tools.xmpp.IRecievable;

import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.location.Location;

/**
 * This class, given a contact id and a contacter_id, retrieves the location of that contact and
 * formats it accordingly.
 * 
 * @author jfredett
 * 
 */
public class RemoteLocation implements IRecievable, ILocatable {

	private String contact_id;
	private Location GPSLocation;
	private String contacter_id;
	private GTalkAgent talkagent;

	public RemoteLocation(String contact_id, String contacter_id) throws MalformedMimeTypeException,
			GTalkFailedException {

		// initialize parameters and GPS locations
		this.contacter_id = contacter_id;
		this.contact_id = contact_id;

		GPSLocation = getGPSLoc();
	}

	@Override
	public IRecievable createRecievable(String from, String msg, String to) {
		this.contacter_id = from;
		this.contact_id = to;
		// parse the message to get the location.
		GPSLocation = parseGPSmsg(msg);

		return this;
	}

	@Override
	public Location getLocation() {
		return GPSLocation;
	}

	@Override
	public String getName() {
		return contact_id;
	}

	@Override
	public Overlay mkOverlay() {
		return new LocationOverlay(GPSLocation);
	}
	
	///////////////////////
	////Private Methods////
	///////////////////////

	private Location parseGPSmsg(String msg) {
		int sep = msg.indexOf(",");
		int end = msg.indexOf(";") - 1;
		double lat = new Double(msg.substring(0, sep));
		double lon = new Double(msg.substring(sep, end));

		Location newLoc = new Location();
		newLoc.setLatitude(lat);
		newLoc.setLongitude(lon);

		return newLoc;
	}

	private String createGPSMessage() {
		Double lat = GPSLocation.getLatitude();
		Double lon = GPSLocation.getLongitude();
		return (lat.toString() + "," + lon.toString() + ";");
	}

	private Location getGPSLoc() throws MalformedMimeTypeException, GTalkFailedException {
		GPSRequest request = new GPSRequest(this.contacter_id, this.contact_id);
		IntentFilter msgfilter = talkagent.sendMessage(request);
		// the way the getMessage method is designed will call the
		// "createRecievable" method, which
		// will do the updating.
		talkagent.getMessage(this, msgfilter);
		// to meet the contract, we just have to return our location, which is
		// updated in the previous line.
		return GPSLocation;
	}

	@Override
	public String getMessage() {
		return createGPSMessage();
	}

	@Override
	public String getRecipient() {
		return contact_id;
	}

	@Override
	public String getSender() {
		return contacter_id;
	}
}
